package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Topic;
import com.ywgt.service.TopicService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin/topic")
@ApiModel("专题管理")
public class TopicController {

    @Autowired
    TopicService topicService;

    /**
     *  page: 1,
     *         limit: 20,
     *         title: undefined,
     *         subtitle: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getTopics(String title, String subtitle, @RequestParam(required = false,defaultValue = "add_time") String sort,
                            @RequestParam(required = false,defaultValue = "desc") String order,
                            @RequestParam(required = false,defaultValue = "1") int page,
                            @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Topic> topics=topicService.getTopics(title,subtitle,page,limit,sort,order);
        List<Topic> items = topics.getResult();
        long total = topics.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Topic topic){
        if(topicService.removeById(topic.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
    @PostMapping("/update")
    public Object update(@RequestBody Topic topic){
        if(topicService.updateById(topic)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/create")
    public Object create(@RequestBody Topic topic){
        if(topicService.save(topic)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
